<template>
  <div class="app-container">
    <el-form :model="queryParam" ref="queryForm" :inline="true">
      <el-form-item label="题干内容：">
        <el-autocomplete
          v-model="queryParam.questionTitle"
          :fetch-suggestions="querySearch"
          placeholder="请输入题干内容"
          clearable
        ></el-autocomplete>
      </el-form-item>
      <el-form-item label="年级：">
        <el-select
          class="select"
          v-model="queryParam.level"
          placeholder="年级"
          @change="levelChange"
          clearable
          @clear="clearLevel"
        >
          <el-option
            v-for="item in levelEnum"
            :key="item.key"
            :value="item.key"
            :label="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学科：">
        <el-select v-model="queryParam.subjectId" clearable class="select">
          <el-option
            v-for="item in subjectFilter"
            :key="item.id"
            :value="item.id"
            :label="item.name + ' ( ' + item.levelName + ' )'"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="题型：">
        <el-select v-model="queryParam.questionType" clearable class="select">
          <el-option
            v-for="item in questionType"
            :key="item.key"
            :value="item.key"
            :label="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">查询</el-button>
        <el-popover placement="bottom" trigger="click">
          <el-button
            type="warning"
            size="mini"
            v-for="item in editUrlEnum"
            :key="item.key"
            @click="$router.push({ path: item.value })"
          >
            {{ item.name }}
          </el-button>
          <el-button slot="reference" type="primary" class="link-left"
            >添加</el-button
          >
        </el-popover>
        <el-popover placement="bottom" trigger="click">
          <el-button type="success" size="mini">
            <a
              href="./static/excel/template.xlsx"
              style="text-decoration-line: none; color: white"
              >下载模板</a
            >
          </el-button>
          <el-button type="success" size="mini">
            <el-upload
              accept=".xlsx"
              action="/api/admin/upload/excel"
              :on-success="handleSuccess"
              :on-error="handleError"
              :before-upload="beforeAvatarUpload"
              :auto-upload="true"
              :show-file-list="false"
              ref="upload"
            >
              模板导入
            </el-upload>
          </el-button>
          <el-button slot="reference" type="primary" class="link-left"
            >导入</el-button
          >
        </el-popover>
        <el-button
          type="danger"
          @click="deleteSelect"
          style="margin-left: 5px"
          :disabled="disabled"
          >删除</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      v-loading="listLoading"
      :data="tableData"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="changeTableSort"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="Id" width="90px" />
      <el-table-column
        prop="subjectId"
        label="学科"
        :formatter="subjectFormatter"
        width="120px"
        show-overflow-tooltip
      />
      <el-table-column
        prop="questionType"
        label="题型"
        :formatter="questionTypeFormatter"
        width="70px"
      />
      <el-table-column prop="shortTitle" label="题干" show-overflow-tooltip />
      <el-table-column
        prop="score"
        label="分数"
        width="80px"
        :sortable="'custom'"
      />
      <el-table-column
        prop="difficult"
        label="难度"
        width="80px"
        :sortable="'custom'"
      />
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="160px"
        :sortable="'custom'"
      />
      <el-table-column label="操作" align="center" width="220px">
        <template slot-scope="{ row }">
          <el-button size="mini" @click="showQuestion(row)">预览</el-button>
          <el-button size="mini" @click="editQuestion(row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="deleteQuestion(row)"
            class="link-left"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParam.pageIndex"
      :limit.sync="queryParam.pageSize"
      @pagination="search"
    />
    <el-dialog
      :visible.sync="questionShow.dialog"
      style="width: 100%; height: 100%"
    >
      <QuestionShow
        :qType="questionShow.qType"
        :question="questionShow.question"
        :qLoading="questionShow.loading"
      />
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters, mapState, mapActions, mapMutations } from "vuex";
import Pagination from "@/components/Pagination";
import QuestionShow from "./components/Show";
import questionApi from "@/api/question";
import subjectApi from "@/api/subject";

export default {
  components: { Pagination, QuestionShow },
  data() {
    return {
      disabled: true,
      multipleSelection: [],
      uploadLoading: false,
      fileList: [], // excel文件列表
      queryParam: {
        questionTitle: null,
        questionType: null,
        level: null,
        subjectId: null,
        pageIndex: 1,
        pageSize: 10,
        sort: "create_time desc",
      },
      subjectFilter: null,
      listLoading: true,
      tableData: [],
      total: 0,
      questionShow: {
        qType: 0,
        dialog: false,
        question: null,
        loading: false,
      },
    };
  },
  created() {
    this.$nextTick(() => {
      subjectApi.list().then((re) => {
        this.subjects = re.response;
        this.subjectFilter = this.subjects;
        this.setSubjects(re.response);
      });
      // this.initSubject();
      this.initQuestionTitleList();
      this.search();
    });
  },
  methods: {
    beforeAvatarUpload(file) {
      let fileName = file.name.substring(file.name.lastIndexOf(".") + 1);
      const extension = fileName === "xls";
      const extension2 = fileName === "xlsx";
      if (!extension && !extension2) {
        this.$message({
          message: "上传文件只能是 xls、xlsx格式！",
          type: "error",
        });
        return false;
      }
      this.listLoading = true;
    },
    changeTableSort(column) {
      //获取字段名称和排序类型
      var fieldName = column.prop;
      var sortingType = column.order;
      this.queryParam.pageIndex = 1;
      let x = "";
      if (fieldName == "score") {
        x = "score";
      } else if (fieldName == "createTime") {
        x = "create_time";
      } else if (fieldName == "difficult") {
        x = "difficult";
      }
      if (sortingType == "descending") {
        this.queryParam.sort = x + " desc";
      } else {
        this.queryParam.sort = x + " asc";
      }
      this.search();
    },
    querySearch(queryString, cb) {
      var questionTitleList = this.questionTitleList;
      var results = queryString
        ? questionTitleList.filter(this.createFilter(queryString))
        : questionTitleList;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (item) => {
        return (
          item.value.toLowerCase().indexOf(queryString.toLowerCase()) != -1
        );
      };
    },
    submitForm() {
      this.queryParam.pageIndex = 1;
      this.search();
    },
    search() {
      this.listLoading = true;
      questionApi.pageList(this.queryParam).then((data) => {
        const re = data.response;
        this.tableData = re.list;
        this.total = re.total;
        this.queryParam.pageIndex = re.pageNum;
        this.listLoading = false;
      });
    },
    levelChange() {
      this.queryParam.subjectId = null;
      this.subjectFilter = this.subjects.filter(
        (data) => data.level === this.queryParam.level
      );
    },
    addQuestion() {
      this.$router.push("/exam/question/edit/singleChoice");
    },
    showQuestion(row) {
      let _this = this;
      this.questionShow.dialog = true;
      this.questionShow.loading = true;
      questionApi.select(row.id).then((re) => {
        _this.questionShow.qType = re.response.questionType;
        _this.questionShow.question = re.response;
        _this.questionShow.loading = false;
      });
    },
    deleteSelect() {
      this.$confirm("是否删除题目?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let _this = this;
        _this.listLoading = true;
        let params = [];
        this.multipleSelection.map((item) => {
          params.push(item.id);
        });
        let query = {
          idList: params,
        };
        questionApi
          .deleteSelect(query)
          .then((re) => {
            if (re.code === 1) {
              _this.search();
              _this.$message.success(re.message);
            } else {
              _this.$message.error(re.message);
            }
            _this.listLoading = false;
          })
          .catch((e) => {
            _this.listLoading = false;
          });
      });
    },
    editQuestion(row) {
      let url = this.enumFormat(this.editUrlEnum, row.questionType);
      this.$router.push({ path: url, query: { id: row.id } });
    },
    deleteQuestion(row) {
      this.$confirm("是否删除题目?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let _this = this;
        questionApi.deleteQuestion(row.id).then((re) => {
          if (re.code === 1) {
            _this.search();
            _this.$message.success(re.message);
          } else {
            _this.$message.error(re.message);
          }
        });
      });
    },
    questionTypeFormatter(row, column, cellValue, index) {
      return this.enumFormat(this.questionType, cellValue);
    },
    subjectFormatter(row, column, cellValue, index) {
      return this.subjectEnumFormat(cellValue);
    },
    clearLevel() {
      this.subjectFilter = this.subjects;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // UploadUrl() {

    //   // 因为action参数是必填项，我们使用二次确认进行文件上传时，直接填上传文件的url会因为没有参数导致api报404，所以这里将action设置为一个返回为空的方法就行，避免抛错
    //   return "";
    // },

    // 文件上传成功时的钩子
    handleSuccess(res, file, fileList) {
      if (res.code === 1) {
        this.$message({
          type: "success",
          message: "导入模板成功",
        });
        this.search();
      } else {
        this.$message.error(res.message);
      }
      this.listLoading = false;
    },
    // 文件上传失败时的钩子
    handleError(err, file, fileList) {
      this.$message.error("文件上传失败");
      this.listLoading = false;
    },
    ...mapActions("exam", {
      initSubject: "initSubject",
      initQuestionTitleList: "initQuestionTitleList",
    }),
    ...mapMutations("exam", ["setSubjects"]),
  },
  computed: {
    ...mapGetters("enumItem", ["enumFormat"]),
    ...mapState("enumItem", {
      questionType: (state) => state.exam.question.typeEnum,
      editUrlEnum: (state) => state.exam.question.editUrlEnum,
      levelEnum: (state) => state.user.levelEnum,
    }),
    ...mapGetters("exam", ["subjectEnumFormat"]),
    //...mapState('exam', { subjects: state => state.subjects })
    ...mapState("exam", {
      questionTitleList: (state) => state.questionTitleList,
    }),
  },
  watch: {
    multipleSelection: {
      handler(newVal, oldVal) {
        console.log(newVal);
        if (newVal && newVal.length > 0) {
          this.disabled = false;
        } else {
          this.disabled = true;
        }
      },
      deep: true,
    },
  },
};
</script>
<style lang="scss">
.select {
  width: 190px;
}
</style>
